package com.lfx.demo.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2024-08-14 20:21:34
 */
public class SemaphoreExample {
    private static final Semaphore semaphore = new Semaphore(1, true);

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(2);


        executorService.submit(() -> {
            try {
                // 尝试获取一个许可
                semaphore.acquire();
                System.out.println("Acquired permit. Now doing some work...");
                // 模拟长时间运行的任务
                Thread.sleep(100000);
                System.out.println("sleep out");
                semaphore.release();
            } catch (InterruptedException e) {
                System.out.println("Task was interrupted while waiting for the semaphore.");
                Thread.currentThread().interrupt(); // 重新设置中断状态
            }
        });

        executorService.submit(() -> {
            try {
                // 尝试获取一个许可
                semaphore.acquire();
                System.out.println("Acquired2 permit. Now doing some work...");
                // 模拟长时间运行的任务
                Thread.sleep(100000);
                System.out.println("sleep2 out");
                semaphore.release();
            } catch (InterruptedException e) {
                System.out.println("Task2 was interrupted while waiting for the semaphore.");
                Thread.currentThread().interrupt(); // 重新设置中断状态
            }
        });

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("JVM is shutting down. Cleaning up resources...");
            // shutdownNow()会中断线程，shutdown()是等待执行完
            executorService.shutdownNow();

            // 等待所有任务完成
            try {
                while (!executorService.awaitTermination(1, java.util.concurrent.TimeUnit.SECONDS)) {
                    System.out.println("All tasks completed.");
                    Thread.sleep(2000);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }));
        // 假设等待一段时间后，决定停止线程池
        Thread.sleep(1000000); // 等待5秒
    }
}
